package com.ytjj.qmyx.users.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.DateUtils;
import com.ytjj.common.enums.AliPayComplaintsStatusEnums;
import com.ytjj.common.model.response.OrdersPayResponse;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.config.SupplyApiConfig;
import com.ytjj.qmyx.users.dao.OrdersDao;
import com.ytjj.qmyx.users.dao.ReturnGoodsDao;
import com.ytjj.qmyx.users.dao.UsersDao;
import com.ytjj.qmyx.users.enums.OrderStatusEnums;
import com.ytjj.qmyx.users.enums.ReturnGoodsStatusEnums;
import com.ytjj.qmyx.users.model.BankerProduct;
import com.ytjj.qmyx.users.model.circle.Product;
import com.ytjj.qmyx.users.model.request.QyOrderReq;
import com.ytjj.qmyx.users.model.response.OrdersForQyResponse;
import com.ytjj.qmyx.users.model.response.QyOrdersResponse;
import com.ytjj.qmyx.users.model.response.ReissueLogisticsResponse;
import com.ytjj.qmyx.users.service.QiYuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RefreshScope
public class QiYuServiceImpl implements QiYuService {

    private static final String APPID = "qyf5f8a721a9415ge6";
    private static final String APPSECRET = "a7fd09486a60e8eb633a5bb93ac6324f";

    private static final String QYTOKEN = "im:qy:token";

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private OrdersDao ordersDao;

    @Resource
    private ReturnGoodsDao returnGoodsDao;

    @Value("${qiyu.api.url:}")
    private String url;

    @Value("${supply.api.shopId}")
    private String shopId;

    @Autowired
    private SupplyApiConfig supplyApiConfig;

    /**
     * 获取token
     */
    private String getTokenApiName = "/get_token";

    /**
     * 用户信息（呼叫）URL
     */
    private String callUserInfoApiName = "/get_call_user_info";

    /**
     * 用户订单接口（在线）URL
     */
    private String getOrderApiName = "/get_order";

    /**
     * 用户订单接口（在线）URL
     */
    private String getCallOrderApiName = "/get_call_order";


    @Override
    public Map<String, Object> getCallUserInfo(String tel) {
        Map<String, Object> result = new HashMap<>();
        Map<String,String> map = usersDao.getCallUserInfoByTel(tel);
        if (map !=null){
            String userName = map.get("user_name");
            String h5Token = map.get("h5_token");

            List<Map<String,String>> list = new ArrayList<>();
            Map<String,String> data = new HashMap<>();
            data.put("key","name");
            data.put("value",userName);
            data.put("label","姓名");
            list.add(data);

            result.put("rlt",0);
            result.put("uid", h5Token);
            result.put("data",list);
            return result;
        }else {
            //仅XXXX系统才调用其他系统接口
            if (StringUtils.isNotEmpty(shopId) && shopId.contains("GUOB")) {
                if (StringUtils.isNotEmpty(url)) {
                    String[] urls = url.split(",");
                    for (String url : urls) {
                        //去另外的系统的查
                        String token = this.getToken(url);
                        if(StringUtils.isEmpty(token)){
                            continue;
                        }
                        Map<String, String> params = new HashMap<>();
                        params.put("appid", APPID);
                        params.put("token", token);
                        params.put("userid", tel);
                        String resultJson = HttpClientUtil.doPostJson(url+callUserInfoApiName, JSON.toJSONString(params));
                        if (StringUtils.isNotBlank(resultJson)) {
                            result = (Map<String, Object>) JSON.parse(resultJson);
                            return result;
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public QyOrdersResponse getOrderFromQy(QyOrderReq qyOrderReq) {
        QyOrdersResponse response = new QyOrdersResponse();
        List<QyOrdersResponse.Order> orders = new ArrayList<>();
        String h5Token = qyOrderReq.getUserid();
        if (StringUtils.isEmpty(h5Token)) {
            response.setRlt(0);
            response.setCount(0);
            response.setOrders(orders);
            return response;
        }
        //查询当前toke用户的所有订单
        String tel = ordersDao.getTelByH5Token(h5Token);
        List<OrdersForQyResponse> orderList = new ArrayList<>();
        if(StringUtils.isNotEmpty(tel)){
            orderList = ordersDao.getOrdersByTel(null,qyOrderReq.getFrom(),qyOrderReq.getCount(),tel);
        }
        Integer total = ordersDao.getOrdersTotalByTel(h5Token,null);
        //获取商品的销售渠道
        List<Integer> productIdList = orderList.stream().filter(item -> null != item.getProductId()).map(OrdersForQyResponse::getProductId).collect(Collectors.toList());
        List<Product> products = productIdList.size() > 0 ? ordersDao.getProductByIds(productIdList) : new ArrayList<>();
        //查供应链商品
        List<Integer> supplyProductIds = products.stream().map(e->e.getSupplyProductId()).collect(Collectors.toList());
        List<BankerProduct> bankerProducts = new ArrayList<>();
        if (!CollectionUtils.isEmpty(supplyProductIds)){
            Map<String,Object> map = new HashMap<>();
            map.put("productIds",supplyProductIds);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", JSON.toJSONString(map), supplyApiConfig.getHeadsMap());
            bankerProducts = JSONObject.parseArray(result, BankerProduct.class);
        }

        //查询供应链异常订单信息
        List<String> childOrderNoList = orderList.stream().filter(item -> !StringUtils.isEmpty(item.getChildOrderNo())).map(OrdersForQyResponse::getChildOrderNo).collect(Collectors.toList());
        List<OrderExceptionNoteResponse> orderExceptionNotes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(childOrderNoList)) {
            OrderExceptionNoteRequest orderExceptionNoteRequest  = new OrderExceptionNoteRequest();
            orderExceptionNoteRequest.setChildOrderNoList(childOrderNoList);
            String json = JSON.toJSONString(orderExceptionNoteRequest);
            String orderExceptionResult = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/selectNoteByChildrenOrderNo", json, supplyApiConfig.getHeadsMap());
            log.info("查询异常单返回:{}",orderExceptionResult);
            if (StringUtils.isNotBlank(orderExceptionResult)) {
                orderExceptionNotes =  JSONObject.parseArray(orderExceptionResult, OrderExceptionNoteResponse.class);
            }
        }
        //查询供应链订单
        List<SupplyOrderQueryResponse> supplyOrderQueryRespons = new ArrayList<>();
        if (!CollectionUtils.isEmpty(childOrderNoList)) {
            SupplyOrderQueryRequest supplyOrderQueryRequest = new SupplyOrderQueryRequest();
            supplyOrderQueryRequest.setChildOrderNo(childOrderNoList);
            String jsonStr = JSON.toJSONString(supplyOrderQueryRequest);
            String orderQueryJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/query", jsonStr, supplyApiConfig.getHeadsMap());
            CommonResult orderQueryResult = JSONObject.parseObject(orderQueryJson, CommonResult.class);
            if (null != orderQueryResult && 200 == orderQueryResult.getCode() &&  null != orderQueryResult.getData()) {
                supplyOrderQueryRespons = JSONObject.parseArray(orderQueryResult.getData().toString(), SupplyOrderQueryResponse.class);
            }
        }

        //查询投诉订单
        List<OrderComplainResponse> complaintsByPayNos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderList)){
            Set<String> orderNos = orderList.stream().map(OrdersForQyResponse::getOrderNo).collect(Collectors.toSet());
            List<OrdersPayResponse> ordersPayResponses = ordersDao.selectResOrderNoByOrderNo(new ArrayList<>(orderNos), 2);
            if(!CollectionUtils.isEmpty(ordersPayResponses)){
                complaintsByPayNos = ordersDao.getComplaintsByPayNos(ordersPayResponses.stream().map(OrdersPayResponse::getResOrderNo).collect(Collectors.toList()));
            }
        }



        for (int i = 0; i < orderList.size(); i++) {
            String orderStatusDesc = "";
            OrdersForQyResponse item = orderList.get(i);
            if ((System.currentTimeMillis() - item.getPayTime().getTime()) / 1000 >= 1800
                    && OrderStatusEnums.WAIT_DELIVERY.getStatus().equals(item.getOrderInfoStatus().toString())) {
                orderStatusDesc = "已出库";
            } else {
                orderStatusDesc = OrderStatusEnums.getStatusDesc(item.getOrderInfoStatus().toString());
            }
            QyOrdersResponse.Order order = new QyOrdersResponse().new Order();
            List<QyOrdersResponse.Block> blocks = new ArrayList<>();

            QyOrdersResponse.Block titleBlock = new QyOrdersResponse().new Block();
            QyOrdersResponse.DataInfo titleData = new QyOrdersResponse().new DataInfo();
            titleData.setKey("title");
            if (shopId.contains("GUOB")){
                titleData.setLabel("【XXXX】");
            } else if (shopId.contains("JUMD")){
                titleData.setLabel("【XXX】");
            } else if (shopId.contains("YQKJ")){
                titleData.setLabel("【易全】");
            } else if (shopId.contains("YGYX")){
                titleData.setLabel("【XXX】");
            } else if (shopId.contains("ZXLP")){
                titleData.setLabel("【益惠严选】");
            } else if (shopId.contains("YXHD")){
                titleData.setLabel("【优享好兑】");
            } else if (shopId.contains("JCYX005")){
                titleData.setLabel("【进程严选】");
            } else {
                titleData.setLabel("");
            }

            titleData.setValue(item.getProductName());
            titleBlock.setIndex(0);
            titleBlock.set_title(true);
            titleBlock.setData(Arrays.asList(titleData));

            //设置详情项
            List<QyOrdersResponse.DataInfo> dataList = new ArrayList<>();
            QyOrdersResponse.DataInfo payTimeData = new QyOrdersResponse().new DataInfo();
            payTimeData.setKey("payTime");
            payTimeData.setLabel("支付时间");
            payTimeData.setValue(DateTimeUtil.TimeToStr(item.getPayTime()));
            dataList.add(payTimeData);



            //收件人信息
            QyOrdersResponse.DataInfo userInfoData = new QyOrdersResponse().new DataInfo();
            userInfoData.setKey("userInfo");
            userInfoData.setLabel("收件人信息");
            userInfoData.setValue(item.getUserName() + "  " + item.getUserPhone());
            dataList.add(userInfoData);

            //收货地址
            QyOrdersResponse.DataInfo receiveAddressData = new QyOrdersResponse().new DataInfo();
            receiveAddressData.setKey("receiveAddress");
            receiveAddressData.setLabel("收货地址");
            receiveAddressData.setValue(item.getUserAddress());
            dataList.add(receiveAddressData);

            //金额
            QyOrdersResponse.DataInfo priceData = new QyOrdersResponse().new DataInfo();
            priceData.setKey("priceData");
            priceData.setLabel("金额");
            priceData.setValue(String.format("商品售价：%s，实付金额：%s", item.getProductPrice(), item.getRealTotalMoney()));
            dataList.add(priceData);

            //商品规格
            QyOrdersResponse.DataInfo productSkuSpec = new QyOrdersResponse().new DataInfo();
            productSkuSpec.setKey("productSkuSpec");
            productSkuSpec.setLabel("规格");
            productSkuSpec.setValue(item.getProductSkuSpec());
            dataList.add(productSkuSpec);

            if (!CollectionUtils.isEmpty(products)) {
                List<Product> productList = products.stream().filter(p -> p.getId().equals(item.getProductId())).collect(Collectors.toList());
                //设置订单销售平台
                if (!CollectionUtils.isEmpty(productList)) {
                    Product product = productList.get(0);
                    item.setSupplyProductId(product.getSupplyProductId());
                    item.setPlatformInfo(product.getPlatformData());
                    //退货地址
                    List<BankerProduct> collect = bankerProducts.stream().filter(sp -> sp.getId().equals(item.getSupplyProductId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        item.setAddressInfo(collect.get(0).getAddressInfo());
                    }
                }
            }

            QyOrdersResponse.DataInfo paySourceData = new QyOrdersResponse().new DataInfo();
            paySourceData.setKey("paySource");
            paySourceData.setLabel("支付渠道");
            paySourceData.setValue("wx".equals(item.getPaySource()) ? "微信" : "alipay".equals(item.getPaySource()) ? "支付宝" : "未知");
            dataList.add(paySourceData);

//            QyOrdersResponse.DataInfo payStatusData = new QyOrdersResponse().new DataInfo();
//            payStatusData.setKey("isPay");
//            payStatusData.setLabel("支付状态");
//            payStatusData.setValue(item.getIsPay() == 1 ? "已支付" : "未支付");
//            dataList.add(payStatusData);

            QyOrdersResponse.DataInfo orderStatusData = new QyOrdersResponse().new DataInfo();
            orderStatusData.setKey("orderStatus");
            orderStatusData.setLabel("订单状态");
            orderStatusData.setValue(orderStatusDesc);
            dataList.add(orderStatusData);

            if(Arrays.asList(4,5,6).contains(item.getOrderInfoStatus())){
                List<YxReturnGoods> returnGoods = returnGoodsDao.getReturnGoods(item.getId());
                if(returnGoods.size() > 0){
                    String returnStatusDesc = ReturnGoodsStatusEnums.getMessageByCode(returnGoods.get(0).getStatus());
                    QyOrdersResponse.DataInfo returnGoodStatusData = new QyOrdersResponse().new DataInfo();
                    returnGoodStatusData.setKey("returnGoodStatus");
                    returnGoodStatusData.setLabel("售后状态");
                    returnGoodStatusData.setValue(returnStatusDesc);
                    dataList.add(returnGoodStatusData);
                }
            }

            //补单状态
            ReissueLogisticsResponse reissueLogistics = ordersDao.getReissueLogistics(item.getChildOrderNo());
            if(null != reissueLogistics){
                QyOrdersResponse.DataInfo reissueStatus = new QyOrdersResponse().new DataInfo();
                reissueStatus.setKey("reissueStatus");
                reissueStatus.setLabel("补单状态");
                String returnStatusDesc = "";
                if(reissueLogistics.getStatus() == 0){
                    returnStatusDesc = "待处理";
                }else if(reissueLogistics.getStatus() == 1){
                    returnStatusDesc = "处理中";
                }else if(reissueLogistics.getStatus() == 2){
                    returnStatusDesc = "处理成功";
                }else if(reissueLogistics.getStatus() == 3){
                    returnStatusDesc = "处理失败";
                }
                if (reissueLogistics.getReissueType() == 2 || reissueLogistics.getReissueType() == 3 || reissueLogistics.getReissueType() == 4){
                    if (StringUtils.isNotEmpty(reissueLogistics.getRecoveryOrderNo())) {
                        returnStatusDesc += "-已寄回";
                    }else {
                        returnStatusDesc += "-等待寄回";
                    }
                }
                reissueStatus.setValue(returnStatusDesc);
                dataList.add(reissueStatus);
            }


            //订单推送时间
            QyOrdersResponse.DataInfo orderSyncTimeData = new QyOrdersResponse().new DataInfo();
            orderSyncTimeData.setKey("orderSyncTime");
            orderSyncTimeData.setLabel("同步时间");
            Date orderSyncTime = null;
            if (!CollectionUtils.isEmpty(supplyOrderQueryRespons)) {
                List<SupplyOrderQueryResponse> collect = supplyOrderQueryRespons.stream().filter(bankerOrder -> bankerOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    orderSyncTime = collect.get(0).getOrderSyncTime();
                }
            }
            orderSyncTimeData.setValue(orderSyncTime == null? "" : DateTimeUtil.format(orderSyncTime,"yyyy-MM-dd HH:mm:ss"));
            dataList.add(orderSyncTimeData);

            //投诉状态
            StringBuffer sb = new StringBuffer();
            List<OrderComplainResponse> orderComplains = complaintsByPayNos.stream().filter(e -> e.getOrderNo().equals(item.getOrderNo())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(orderComplains)){
                for (OrderComplainResponse orderComplain : orderComplains) {
                    String complainStatus = orderComplain.getComplainStatus();
                    String complainStatusText = "";
                    if("支付宝".equals(orderComplain.getPlatForm())){
                        String msg = AliPayComplaintsStatusEnums.getMsg(complainStatus);
                        if(StringUtils.isEmpty(msg)){
                            complainStatusText = complainStatus;
                        }
                        complainStatusText = "【"+complainStatusText+"】";
                    }else if("微信".equals(orderComplain.getPlatForm())){
                        //投诉单状态 PENDING-待处理,PROCESSING-处理中,PROCESSED-已处理完成
                        if("PENDING".equals(complainStatus)){
                            complainStatusText = "【待处理】";
                        }else if("PROCESSING".equals(complainStatus)){
                            complainStatusText = "【处理中】";
                        }else if("PROCESSED".equals(complainStatus)){
                            complainStatusText = "【已处理完成】";
                        }
                    }
                    sb.append(orderComplain.getPlatForm() + " 投诉时间：" + orderComplain.getComplaintTime() + " | " + complainStatusText + "处理时间：" + orderComplain.getHandleTime());
                }
            }
            QyOrdersResponse.DataInfo complaintData = new QyOrdersResponse().new DataInfo();
            complaintData.setKey("complaintInfo");
            complaintData.setLabel("投诉状态");
            complaintData.setValue(sb.toString());
            dataList.add(complaintData);

            //供应商id
            QyOrdersResponse.DataInfo bankerIdData = new QyOrdersResponse().new DataInfo();
            bankerIdData.setKey("bankerId");
            bankerIdData.setLabel("供应商id");
            bankerIdData.setValue(item.getBankerId().toString());
            dataList.add(bankerIdData);

            QyOrdersResponse.DataInfo supplyProductIdData = new QyOrdersResponse().new DataInfo();
            supplyProductIdData.setKey("supplyProductId");
            supplyProductIdData.setLabel("供应商商品id");
            supplyProductIdData.setValue(item.getSupplyProductId().toString());
            dataList.add(supplyProductIdData);

            QyOrdersResponse.DataInfo platformData = new QyOrdersResponse().new DataInfo();
            platformData.setKey("platformData");
            platformData.setLabel("销售渠道");

            String accountMark="";
            if (("hzwx0001@163.com".equals(item.getAccount()) || "huiyd01@163.com".equals(item.getAccount()))){

                LocalDateTime targetDateTime = LocalDateTime.parse("2025-01-12 10:30", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                // 比较当前日期时间与目标日期时间
                if (LocalDateTime.now().isBefore(targetDateTime)) {
                    accountMark = "走线下退款";
                }
            }
            platformData.setValue(item.getPlatformInfo()+(org.apache.commons.lang3.StringUtils.isNotBlank(item.getDomainUrl()) ?"_非支付宝" : "_支付宝渠道" )+"   "+item.getAccount()+"   "+accountMark);
            dataList.add(platformData);


            QyOrdersResponse.DataInfo addressInfoData = new QyOrdersResponse().new DataInfo();
            addressInfoData.setKey("addressInfo");
            addressInfoData.setLabel("退货地址");
            addressInfoData.setValue(item.getAddressInfo());
            dataList.add(addressInfoData);

            QyOrdersResponse.DataInfo expressInfoData = new QyOrdersResponse().new DataInfo();
            expressInfoData.setKey("expressInfo");
            expressInfoData.setLabel("发货物流");
            String expressInfo = item.getExpressCompanyNo() + " " + StringUtils.trimToNull(item.getExpressNo());
            expressInfoData.setValue(expressInfo.equals("null null") ? null : expressInfo);
            dataList.add(expressInfoData);

            //发货物流最新记录
            if(StringUtils.isNotBlank(item.getExpressNo()) && StringUtils.isNotBlank(item.getExpressCompanyNo())){
                //查订单的物流
                Map<String,String> request = new HashMap<>();
                request.put("expressCode",item.getExpressCompanyNo());
                request.put("expressNo",item.getExpressNo());
                request.put("tel",item.getUserPhone());
                String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/express/getLogisticsInfo",request, supplyApiConfig.getHeadsMap());
                CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
                if (null != commonResult && 200 == commonResult.getCode() &&  null != commonResult.getData()) {
                    List<QueryTrackData> data = JSONArray.parseArray(commonResult.getData().toString(), QueryTrackData.class);
                    //需求：显示最新2个节点物流信息即可
                    for (int j = 0; j < 2 && data.size() > j; j++) {
                        QyOrdersResponse.DataInfo expressData = new QyOrdersResponse().new DataInfo();
                        expressData.setKey("latestExpress"+j);
                        QueryTrackData queryTrackData = data.get(j);
                        expressData.setLabel(queryTrackData.getFtime());
                        expressData.setValue(queryTrackData.getContext());
                        dataList.add(expressData);
                    }
                }
            }

            //跟单备注
            QyOrdersResponse.DataInfo orderExceptionNoteStrData = new QyOrdersResponse().new DataInfo();
            orderExceptionNoteStrData.setKey("orderExceptionNoteStr");
            orderExceptionNoteStrData.setLabel("跟单备注");
            String orderExceptionNoteStr= Strings.EMPTY;
            if (!CollectionUtils.isEmpty(orderExceptionNotes)) {
                List<OrderExceptionNoteResponse> notes = orderExceptionNotes.stream().filter(item2 -> item2.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(notes)) {
                    orderExceptionNoteStr = notes.get(0).getAdminName()+ " " + notes.get(0).getContent() +
                            " 时间为"  + DateTimeUtil.format(notes.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss");
                }
            }
            orderExceptionNoteStrData.setValue(orderExceptionNoteStr);
            dataList.add(orderExceptionNoteStrData);


            QyOrdersResponse.Block blockDetail = new QyOrdersResponse().new Block();
            blockDetail.setData(dataList);
            blockDetail.setIndex(1);
            blockDetail.set_title(false);
            blocks.add(titleBlock);
            blocks.add(blockDetail);

            order.setIndex(i);
            order.setBlocks(blocks);
            orders.add(order);
        }
        response.setRlt(0);
        response.setCount(total);
        response.setOrders(orders);

        //优先返回XXXX系统的订单，XXXX系统没有订单的时候，才调用其他系统接口
        if (total == 0 && StringUtils.isNotEmpty(shopId) && shopId.contains("GUOB")) {
            if (StringUtils.isNotEmpty(url)) {
                //获取平台系统接口
                String[] urls = url.split(",");
                //仅XXXX系统才调用另外系统接口
                for (String itemUrl : urls) {
                    //去其他几个平台系统查询
                    String token = this.getToken(itemUrl);
                    if(StringUtils.isEmpty(token)){
                        continue;
                    }
                    qyOrderReq.setToken(token);
                    try {
                        String resultJson = HttpClientUtil.doPostJson(itemUrl + getOrderApiName, JSON.toJSONString(qyOrderReq));
                        Gson gson=new Gson();
                        QyOrdersResponse result = gson.fromJson(resultJson, QyOrdersResponse.class);
                        if (null != result && !CollectionUtils.isEmpty(result.getOrders())) {
                            return result;
                        }
                    } catch (Exception e) {
                        log.error("调用另外系统查询在线客服聊天订单出错:",e);
                    }
                }
            }
        }
        return response;
    }

    @Override
    public QyOrdersResponse getOrderFromQyCall(QyOrderReq qyOrderReq) {
        QyOrdersResponse response = new QyOrdersResponse();
        List<QyOrdersResponse.Order> orders = new ArrayList<>();
        String tel = qyOrderReq.getUserid();
        if (StringUtils.isEmpty(tel)) {
            response.setRlt(0);
            response.setCount(0);
            response.setOrders(orders);
            return response;
        }
        List<OrdersForQyResponse> orderList = ordersDao.getOrdersByTel(null,qyOrderReq.getFrom(),qyOrderReq.getCount(),tel);
        Integer total = ordersDao.getOrdersTotalByTel(null,tel);
        //获取商品的销售渠道
        List<Integer> productIdList = orderList.stream().filter(item -> null != item.getProductId()).map(OrdersForQyResponse::getProductId).collect(Collectors.toList());
        List<Product> products = productIdList.size() > 0 ? ordersDao.getProductByIds(productIdList) : new ArrayList<>();
        //查供应链商品
        List<Integer> supplyProductIds = products.stream().map(e->e.getSupplyProductId()).collect(Collectors.toList());
        List<BankerProduct> bankerProducts = new ArrayList<>();
        if (!CollectionUtils.isEmpty(supplyProductIds)){
            Map<String,Object> map = new HashMap<>();
            map.put("productIds",supplyProductIds);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", JSON.toJSONString(map), supplyApiConfig.getHeadsMap());
            bankerProducts = JSONObject.parseArray(result, BankerProduct.class);
        }

        //查询供应链异常订单信息
        List<String> childOrderNoList = orderList.stream().filter(item -> !StringUtils.isEmpty(item.getChildOrderNo())).map(OrdersForQyResponse::getChildOrderNo).collect(Collectors.toList());
        List<OrderExceptionNoteResponse> orderExceptionNotes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(childOrderNoList)) {
            OrderExceptionNoteRequest orderExceptionNoteRequest  = new OrderExceptionNoteRequest();
            orderExceptionNoteRequest.setChildOrderNoList(childOrderNoList);
            String json = JSON.toJSONString(orderExceptionNoteRequest);
            String orderExceptionResult = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/selectNoteByChildrenOrderNo", json, supplyApiConfig.getHeadsMap());
            log.info("查询异常单返回:{}",orderExceptionResult);
            if (StringUtils.isNotBlank(orderExceptionResult)) {
                orderExceptionNotes =  JSONObject.parseArray(orderExceptionResult, OrderExceptionNoteResponse.class);
            }
        }
        //查询供应链订单
        List<SupplyOrderQueryResponse> supplyOrderQueryRespons = new ArrayList<>();
        if (CollectionUtils.isEmpty(childOrderNoList)) {
            SupplyOrderQueryRequest supplyOrderQueryRequest = new SupplyOrderQueryRequest();
            supplyOrderQueryRequest.setChildOrderNo(childOrderNoList);
            String jsonStr = JSON.toJSONString(supplyOrderQueryRequest);
            String orderQueryJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/query", jsonStr, supplyApiConfig.getHeadsMap());
            CommonResult orderQueryResult = JSONObject.parseObject(orderQueryJson, CommonResult.class);
            if (null != orderQueryResult && 200 == orderQueryResult.getCode() &&  null != orderQueryResult.getData()) {
                supplyOrderQueryRespons = JSONObject.parseArray(orderQueryResult.getData().toString(), SupplyOrderQueryResponse.class);
            }
        }

        //查询投诉订单
        List<OrderComplainResponse> complaintsByPayNos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(orderList)){
            Set<String> orderNos = orderList.stream().map(OrdersForQyResponse::getOrderNo).collect(Collectors.toSet());
            List<OrdersPayResponse> ordersPayResponses = ordersDao.selectResOrderNoByOrderNo(new ArrayList<>(orderNos), 2);
            if(!CollectionUtils.isEmpty(ordersPayResponses)){
                complaintsByPayNos = ordersDao.getComplaintsByPayNos(ordersPayResponses.stream().map(OrdersPayResponse::getResOrderNo).collect(Collectors.toList()));
            }
        }

        for (int i = 0; i < orderList.size(); i++) {
            String orderStatusDesc = "";
            OrdersForQyResponse item = orderList.get(i);
            if ((System.currentTimeMillis() - item.getPayTime().getTime()) / 1000 >= 1800
                    && OrderStatusEnums.WAIT_DELIVERY.getStatus().equals(item.getOrderInfoStatus().toString())) {
                orderStatusDesc = "已出库";
            } else {
                orderStatusDesc = OrderStatusEnums.getStatusDesc(item.getOrderInfoStatus().toString());
            }
            QyOrdersResponse.Order order = new QyOrdersResponse().new Order();
            List<QyOrdersResponse.Block> blocks = new ArrayList<>();

            QyOrdersResponse.Block titleBlock = new QyOrdersResponse().new Block();
            QyOrdersResponse.DataInfo titleData = new QyOrdersResponse().new DataInfo();
            titleData.setKey("title");
            if (shopId.contains("GUOB")){
                titleData.setLabel("【XXXX】");
            } else if (shopId.contains("JUMD")){
                titleData.setLabel("【XXX】");
            } else if (shopId.contains("YQKJ")){
                titleData.setLabel("【易全】");
            } else if (shopId.contains("YGYX")){
                titleData.setLabel("【XXX】");
            } else if (shopId.contains("ZXLP")){
                titleData.setLabel("【益惠严选】");
            } else if (shopId.contains("YXHD")){
                titleData.setLabel("【优享好兑】");
            } else if (shopId.contains("JCYX005")){
                titleData.setLabel("【进程严选】");
            } else {
                titleData.setLabel("");
            }
            titleData.setValue(item.getProductName());
            titleBlock.setIndex(0);
            titleBlock.set_title(true);
            titleBlock.setData(Arrays.asList(titleData));

            //设置详情项
            List<QyOrdersResponse.DataInfo> dataList = new ArrayList<>();
            QyOrdersResponse.DataInfo payTimeData = new QyOrdersResponse().new DataInfo();
            payTimeData.setKey("payTime");
            payTimeData.setLabel("支付时间");
            payTimeData.setValue(DateTimeUtil.TimeToStr(item.getPayTime()));
            dataList.add(payTimeData);


            QyOrdersResponse.DataInfo userInfoData = new QyOrdersResponse().new DataInfo();
            userInfoData.setKey("userInfo");
            userInfoData.setLabel("收件人信息");
            userInfoData.setValue(item.getUserName() + "  " + item.getUserPhone());
            dataList.add(userInfoData);

            //收货地址
            QyOrdersResponse.DataInfo receiveAddressData = new QyOrdersResponse().new DataInfo();
            receiveAddressData.setKey("receiveAddress");
            receiveAddressData.setLabel("收货地址");
            receiveAddressData.setValue(item.getUserAddress());
            dataList.add(receiveAddressData);


            QyOrdersResponse.DataInfo priceData = new QyOrdersResponse().new DataInfo();
            priceData.setKey("priceData");
            priceData.setLabel("金额");
            priceData.setValue(String.format("商品售价：%s，实付金额：%s", item.getProductPrice(), item.getRealTotalMoney()));
            dataList.add(priceData);

            if (!CollectionUtils.isEmpty(products)) {
                List<Product> productList = products.stream().filter(p -> p.getId().equals(item.getProductId())).collect(Collectors.toList());
                //设置订单销售平台
                if (!CollectionUtils.isEmpty(productList)) {
                    Product product = productList.get(0);
                    item.setSupplyProductId(product.getSupplyProductId());
                    item.setPlatformInfo(product.getPlatformData());
                    //退货地址
                    List<BankerProduct> collect = bankerProducts.stream().filter(sp -> sp.getId().equals(item.getSupplyProductId())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(collect)){
                        item.setAddressInfo(collect.get(0).getAddressInfo());
                    }
                }
            }

            QyOrdersResponse.DataInfo paySourceData = new QyOrdersResponse().new DataInfo();
            paySourceData.setKey("paySource");
            paySourceData.setLabel("支付渠道");
            paySourceData.setValue("wx".equals(item.getPaySource()) ? "微信" : "alipay".equals(item.getPaySource()) ? "支付宝" : "未知");
            dataList.add(paySourceData);

//            QyOrdersResponse.DataInfo payStatusData = new QyOrdersResponse().new DataInfo();
//            payStatusData.setKey("isPay");
//            payStatusData.setLabel("支付状态");
//            payStatusData.setValue(item.getIsPay() == 1 ? "已支付" : "未支付");
//            dataList.add(payStatusData);

            QyOrdersResponse.DataInfo orderStatusData = new QyOrdersResponse().new DataInfo();
            orderStatusData.setKey("orderStatus");
            orderStatusData.setLabel("订单状态");
            orderStatusData.setValue(orderStatusDesc);
            dataList.add(orderStatusData);

            if(Arrays.asList(4,5,6).contains(item.getOrderInfoStatus())){
                List<YxReturnGoods> returnGoods = returnGoodsDao.getReturnGoods(item.getId());
                if(returnGoods.size() > 0){
                    String returnStatusDesc = ReturnGoodsStatusEnums.getMessageByCode(returnGoods.get(0).getStatus());
                    QyOrdersResponse.DataInfo returnGoodStatusData = new QyOrdersResponse().new DataInfo();
                    returnGoodStatusData.setKey("returnGoodStatus");
                    returnGoodStatusData.setLabel("售后状态");
                    returnGoodStatusData.setValue(returnStatusDesc);
                    dataList.add(returnGoodStatusData);
                }
            }

            //订单同步时间
            QyOrdersResponse.DataInfo orderSyncTimeData = new QyOrdersResponse().new DataInfo();
            orderSyncTimeData.setKey("orderSyncTime");
            orderSyncTimeData.setLabel("同步时间");
            Date orderSyncTime = null;
            if (!CollectionUtils.isEmpty(supplyOrderQueryRespons)) {
                List<SupplyOrderQueryResponse> collect = supplyOrderQueryRespons.stream().filter(bankerOrder -> bankerOrder.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    orderSyncTime = collect.get(0).getOrderSyncTime();
                }
            }
            orderSyncTimeData.setValue(orderSyncTime == null? "" : DateTimeUtil.format(orderSyncTime,"yyyy-MM-dd HH:mm:ss"));
            dataList.add(orderSyncTimeData);


            //投诉状态
            StringBuffer sb = new StringBuffer();
            List<OrderComplainResponse> orderComplains = complaintsByPayNos.stream().filter(e -> e.getOrderNo().equals(item.getOrderNo())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(orderComplains)){
                for (OrderComplainResponse orderComplain : orderComplains) {
                    String complainStatus = orderComplain.getComplainStatus();
                    String complainStatusText = "";
                    if("支付宝".equals(orderComplain.getPlatForm())){
                        String msg = AliPayComplaintsStatusEnums.getMsg(complainStatus);
                        if(StringUtils.isEmpty(msg)){
                            complainStatusText = complainStatus;
                        }
                        complainStatusText = "【"+complainStatusText+"】";
                    }else if("微信".equals(orderComplain.getPlatForm())){
                        //投诉单状态 PENDING-待处理,PROCESSING-处理中,PROCESSED-已处理完成
                        if("PENDING".equals(complainStatus)){
                            complainStatusText = "【待处理】";
                        }else if("PROCESSING".equals(complainStatus)){
                            complainStatusText = "【处理中】";
                        }else if("PROCESSED".equals(complainStatus)){
                            complainStatusText = "【已处理完成】";
                        }
                    }
                    sb.append(orderComplain.getPlatForm() + " 投诉时间：" + orderComplain.getComplaintTime() + " | " + complainStatusText + "处理时间：" + orderComplain.getHandleTime());
                }
            }
            QyOrdersResponse.DataInfo complaintData = new QyOrdersResponse().new DataInfo();
            complaintData.setKey("complaintInfo");
            complaintData.setLabel("投诉状态");
            complaintData.setValue(sb.toString());
            dataList.add(complaintData);

            //供应商id
            QyOrdersResponse.DataInfo bankerIdData = new QyOrdersResponse().new DataInfo();
            bankerIdData.setKey("bankerId");
            bankerIdData.setLabel("供应商id");
            bankerIdData.setValue(item.getBankerId().toString());
            dataList.add(bankerIdData);

            QyOrdersResponse.DataInfo supplyProductIdData = new QyOrdersResponse().new DataInfo();
            supplyProductIdData.setKey("supplyProductId");
            supplyProductIdData.setLabel("供应商商品id");
            supplyProductIdData.setValue(item.getSupplyProductId().toString());
            dataList.add(supplyProductIdData);

            QyOrdersResponse.DataInfo platformData = new QyOrdersResponse().new DataInfo();
            platformData.setKey("platformData");
            platformData.setLabel("销售渠道");
            platformData.setValue(item.getPlatformInfo()+(org.apache.commons.lang3.StringUtils.isNotBlank(item.getDomainUrl()) ?"_非支付宝" : "_支付宝渠道" ));
            dataList.add(platformData);


            QyOrdersResponse.DataInfo addressInfoData = new QyOrdersResponse().new DataInfo();
            addressInfoData.setKey("addressInfo");
            addressInfoData.setLabel("退货地址");
            addressInfoData.setValue(item.getAddressInfo());
            dataList.add(addressInfoData);

            QyOrdersResponse.DataInfo expressInfoData = new QyOrdersResponse().new DataInfo();
            expressInfoData.setKey("expressInfo");
            expressInfoData.setLabel("发货物流");
            String expressInfo = item.getExpressCompanyNo() + " " + StringUtils.trimToNull(item.getExpressNo());
            expressInfoData.setValue(expressInfo.equals("null null") ? null : expressInfo);
            dataList.add(expressInfoData);

            //发货物流最新记录
            if(StringUtils.isNotBlank(item.getExpressNo()) && StringUtils.isNotBlank(item.getExpressCompanyNo())){
                //查订单的物流
                Map<String,String> request = new HashMap<>();
                request.put("expressCode",item.getExpressCompanyNo());
                request.put("expressNo",item.getExpressNo());
                request.put("tel",item.getUserPhone());
                String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/express/getLogisticsInfo",request, supplyApiConfig.getHeadsMap());
                CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
                if (null != commonResult && 200 == commonResult.getCode() &&  null != commonResult.getData()) {
                    List<QueryTrackData> data = JSONArray.parseArray(commonResult.getData().toString(), QueryTrackData.class);
                    for (int j = 0; j < 2 && data.size() > j; j++) {
                        QyOrdersResponse.DataInfo expressData = new QyOrdersResponse().new DataInfo();
                        expressData.setKey("latestExpress"+j);
                        QueryTrackData queryTrackData = data.get(j);
                        expressData.setLabel(queryTrackData.getFtime());
                        expressData.setValue(queryTrackData.getContext());
                        dataList.add(expressData);
                    }
                }
            }


            //跟单备注
            QyOrdersResponse.DataInfo orderExceptionNoteStrData = new QyOrdersResponse().new DataInfo();
            orderExceptionNoteStrData.setKey("orderExceptionNoteStr");
            orderExceptionNoteStrData.setLabel("跟单备注");
            String orderExceptionNoteStr= Strings.EMPTY;
            if (!CollectionUtils.isEmpty(orderExceptionNotes)) {
                List<OrderExceptionNoteResponse> notes = orderExceptionNotes.stream().filter(item2 -> item2.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(notes)) {
                    orderExceptionNoteStr = notes.get(0).getAdminName()+ " " + notes.get(0).getContent() +
                            " 时间为"  + DateTimeUtil.format(notes.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss");
                }
            }
            orderExceptionNoteStrData.setValue(orderExceptionNoteStr);
            dataList.add(orderExceptionNoteStrData);

            QyOrdersResponse.Block blockDetail = new QyOrdersResponse().new Block();
            blockDetail.setData(dataList);
            blockDetail.setIndex(1);
            blockDetail.set_title(false);
            blocks.add(titleBlock);
            blocks.add(blockDetail);

            order.setIndex(i);
            order.setBlocks(blocks);
            orders.add(order);
        }
        response.setRlt(0);
        response.setCount(total);
        response.setOrders(orders);

        //仅XXXX系统才调用其他系统接口
        if (total == 0 && StringUtils.isNotEmpty(shopId) && shopId.contains("GUOB")) {
            if (StringUtils.isNotEmpty(url)) {
                //获取平台系统接口
                String[] urls = url.split(",");
                //仅XXXX系统才调用另外系统接口
                for (String itemUrl : urls) {
                    //去其他系统查询
                    //去另外的系统的查
                    String token = this.getToken(itemUrl);
                    if(StringUtils.isEmpty(token)){
                        continue;
                    }
                    qyOrderReq.setToken(token);
                    try {
                        String resultJson = HttpClientUtil.doPostJson(itemUrl + getCallOrderApiName, JSON.toJSONString(qyOrderReq));
                        Gson gson=new Gson();
                        QyOrdersResponse result = gson.fromJson(resultJson, QyOrdersResponse.class);
                        if (null != result && !CollectionUtils.isEmpty(result.getOrders())) {
                            return result;
                        }
                    } catch (Exception e) {
                        log.error("调用另外系统查询呼叫订单出错:",e);
                    }
                }
            }
        }
        return response;
    }

    /**
     * 获取当前curUrl的token
     */
    public String getToken(String curUrl){
        //获取改系统的token
        Map<String, String> request = new HashMap<>();
        request.put("appid", APPID);
        request.put("appsecret", APPSECRET);
        String resultJson = HttpClientUtil.doGet(curUrl+getTokenApiName, request);
        if (StringUtils.isNotBlank(resultJson)) {
            Map<String,Object> result = (Map<String, Object>) JSON.parse(resultJson);
            if(!CollectionUtils.isEmpty(result)){
                String token = Optional.ofNullable(result.get("token")).orElse("").toString();
                return token;
            }
        }
        return null;
    }
}
